package com.xing.binbackend.topology.remote;

import com.fasterxml.jackson.databind.JsonNode;
import com.xing.binbackend.topology.model.CmdbConfig;
import com.xing.binbackend.topology.model.CmdbRelation;
import com.xing.binbackend.util.ReadFileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Component
public class CmdbService {
    private final CmdbClientService cmdbClientService;
    private final ReadFileUtils readFileUtils;

    public CmdbService(CmdbClientService cmdbClientService, ReadFileUtils readFileUtils) {
        this.cmdbClientService = cmdbClientService;
        this.readFileUtils = readFileUtils;
    }

    private final Map<String, Map<String, JsonNode>> cmdbDataMap = new HashMap<>();

    public void initializeData(String ip) {
        //  根据配置文件 cmdb_config 加载全量CMDB数据
        List<CmdbConfig> cmdbConfigs = readFileUtils.readCmdbConfigs();
        for (CmdbConfig config : cmdbConfigs) {
            List<JsonNode> dataList = queryDataFromCmdb(ip, config);
            Map<String, JsonNode> map =
                    dataList.stream().collect(Collectors.toMap(node -> node.path("id").asText(),
                            Function.identity()));
            cmdbDataMap.put(config.getSourceResType(), map);
        }
        //  根据配置文件 cmdb_config 加载关系


    }

    public void processCmdbRelations(String ip, String jsonFilePath) throws IOException {
        List<CmdbRelation> cmdbRelations = readFileUtils.readCmdbRelations();
        // 遍历第一个
        for (CmdbRelation relation : cmdbRelations) {
//            List<JsonNode> dataList = queryDataFromCmdb(ip, relation);
            // 如果 reach true 就要返回key
//            if (!relation.isReachTarget()) {
//                updateLoadingCache(ip, relation.getQueryCIName(), dataList);
//            } else {
//            }
        }
    }

    private List<JsonNode> queryDataFromCmdb(String ip, CmdbConfig config) {
        switch (config.getSourceCIType()) {
            case "INSTANCE":
                return cmdbClientService.queryInstances(ip, config.getSourceResType(),
                        config.getSourceSelects(), "");
            case "RELATION":
                return cmdbClientService.queryRelations(ip, config.getSourceResType(),
                        config.getSourceSelects(), "");
            default:
                return Collections.emptyList();
        }
    }
}